<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/6/7
 * Time: 1:51
 */

namespace app\api\controller\v8;

use app\api\controller\v2\Auth;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\common\model\FortuneCache;
use app\common\model\FortuneNote;
use app\common\model\Recode;
use think\Log;


/**
 * @title 每日运势相关接口
 * @desc
 * @url
 * @version 1.3.0
 * Class Fortune
 * @package app\api\controller\v2
 */
class Fortune extends Auth
{
    protected $nodel;
    protected $active_switch;

    public function _initialize()
    {
        parent::_initialize();

        $this->nodel = config('code.nodel');
        $this->active_switch = false;
//        $this->active_switch = checktime();
    }

    /**
     * @title 每日运势详情
     * @method GET
     * @desc
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */

    public function index()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $rid = input('get.rid/d', 0);
        // 当前时间
        $time = strtotime(input('get.time/s'));

        if (!$rid) throw new ApiException('档案信息获取失败');
        $uid = (int)$this->user['id'];

        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        //获取日运详情数据
        $data = (new FortuneCache())->getIndexInfo($uid, $time, $rid, $this->active_switch);

        return show(200, '加载成功', $data);
    }

    /**
     * @title 根据年月获取日记标识
     * @method GET
     * @desc
     * @return \think\response\Json
     * @throws ApiException
     */
    public function note_time()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }

        // 当前查看的具体日期
        $time = strtotime(date('Y-m', strtotime(input('get.time'))));

        $rid = input('get.rid/d');

        $uid = $this->user['id'];

        $recode = (new Recode())->getRecode(['id' => $rid]);
        if (!$recode || $recode['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        $vipExpireTime = 0;
        if ($recode['isself'] && Util::CheckAppVersion('2.10.5') !== '小')
        {
            $vipInfo = (new ZlUserVip())->getInfoById($this->user['id']);
            if ($vipInfo['is_valid'] === 1 && $vipInfo['end_time'] > $this->request->time())
            {
                $vipExpireTime = $vipInfo['end_time'];
            }
        }

        $arr = (new FortuneCache())->getFortuneCalendar($rid, $time, $uid, $vipExpireTime);

        return show(200, '成功', $arr);
    }

    /**
     * @title 新建日记
     * @method POST
     * @desc
     * @return \think\response\Json
     * @throws ApiException
     */
    public function save()
    {
        if (!request()->isPost())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $content = htmlspecialchars(input('post.content'));
        $time = strtotime(input('post.time/s'));
        $state = input('post.state/d');
        $mood = input('post.mood/d');
        $from = input('post.from/d');
        $now_time = time();
        $uid = $this->user['id'];

        $RecodeModel = new Recode();
        //        获取档案id
        $recode = $RecodeModel->getSelfRecode(['uid' => $uid]);

        if (!$recode)
        {
            return show(config('code.error'), '档案不存在');
        }

//        $arr = (new \app\common\model\Fortune())->getUserUnlockFortune(['uid' => $uid, 'time' => $time, 'rid' => $rid['id']]);

        $arr = \app\common\cachemodel\FortuneCache::CheckFortuneSevenUnlockStatus($uid, $recode['id'], $time);
        $is_unlock = $arr['is_unlock'];

        //判断当天是否解锁
        if ($is_unlock)
        {
            $FortuneNoteModel = new FortuneNote();
            $note_id = $FortuneNoteModel->saveFortuneNote(['rid' => $recode['id'], 'uid' => $uid, 'content' => $content, 'from' => $from, 'state' => $state, 'mood' => $mood, 'time' => $time, 'create_time' => $now_time]);
            if ($note_id === false)
            {
                return show(config('code.error'), $FortuneNoteModel->getError());
            }

        } else
        {
            return show(config('code.error'), '您需要解锁当天后,才可添加日记');
        }
        $data = [
            "id" => $note_id,
            "create_time" => date('Y-m-d H:i:s', $now_time),
            "content" => $content,
            "state" => $state,
            "mood" => $mood,
            "from" => [
                "rid" => $recode['id'],
                "time" => date('Y-m-d', $time),
                "remark" => "每日运势",
                "icon_url" => "https:\/\/dev-oss.goddessxzns.com\/test\/fortune\/fortune_thumb.png",
            ],
        ];

        return show(config('code.success'), 'Success', $data);
    }

    /**
     * @title 编辑日记
     * @method PUT
     * @desc
     * @return \think\response\Json
     * @throws ApiException
     * @throws Exception
     */
    public function update()
    {
        if (!request()->isPut())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $id = input('param.id/d');
        $content = htmlspecialchars(input('param.content'));
        $state = input('param.state/d');
        $mood = input('param.mood/d');

        $RecodeModel = new Recode();
        $FortuneNoteModel = new FortuneNote();
        //        获取档案id
        $recode = $RecodeModel->getSelfRecode(['uid' => $this->user['id']]);
        if (!$recode)
        {
            return show(config('code.error'), '档案不存在');
        }
        $data = [
            'content' => $content,
            'state' => $state,
            'mood' => $mood,
        ];
        if (trim($content) == '')
        {
            return show(config('code.error'), '内容不能为空');
        }

        $array = $FortuneNoteModel->UpdateData($id, $data);
        if ($array)
        {
            $array['create_time'] = date('Y-m-d H:i:s', $array['update_time']);
            $array['from']['time'] = date('Y-m-d', $array['from']['time']);
        }
        return show(200, '修改成功', $array);
    }

    /**
     * @title 运势日记列表
     * @desc
     * @return \think\response\Json
     * @throws ApiException
     */
    public function note()
    {
        if (!request()->isGet())
        {
            return show(config('code.error'), '未知操作', [], 403);
        }
        $page = input('get.page/d', 1);
        $uid = $this->user['id'];
        $map = ['uid' => $uid, 'isself' => 1];

        $RecodeModel = new Recode();
        $FortuneNoteModel = new FortuneNote();

        $recode_info = $RecodeModel->getSelfRecode($map);
        if (!$recode_info)
        {
            return show(config('code.error'), '档案不存在');
        }

        $map['rid'] = $recode_info['id'];
        $map['page'] = $page;
        try
        {
            $data = $FortuneNoteModel->getListPage($map);
        }
        catch (\Exception $e)
        {
            Log::write('获取运势日记信息失败' . $e->getMessage() . var_export(request()->param(), true), 'error', true);
            $data = [
                'total' => 0,
                'per_page' => 10,
                'current_page' => $page,
                'last_page' => 1,
                'data' => [],
            ];
        }

        if (isset($data['data']) && !empty($data['data']))
        {
            $array = [];
            foreach ($data['data'] as $k => $v)
            {
                $array[] = [
                    'id' => (int)$v['id'],
                    'create_time' => date('Y-m-d H:i:s', $v['create_time']),
                    'content' => $v['content'],
                    'state' => (int)$v['state'],
                    'mood' => (int)$v['mood'],
                    'from' => [
                        'rid' => (int)$v['rid'],
                        'time' => date('Y-m-d', $v['time']),
                        'remark' => '每日运势',
                        'icon_url' => config('fortune.thumb'),
                    ],
                ];
            }

            $data['data'] = $array;
            return show(200, '列表加载成功', $data);
        }
        return show(200, '还没有运势日记，您可以为每日运势打分哦~', $data);
    }
}
